package com.itheima.Filter;

import com.itheima.util.JwtUtils;
import com.itheima.utils.CurrentHolder;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;


@Slf4j
@Component
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //获取请求url
        String url = request.getRequestURL().toString();

        //判断请求url中是否包含login,如果包含,说明是登录操作,放行。
        if(url.contains("login")){
            log.info("登录请求,直接放行");
            chain.doFilter(request, response);
            return;
        }

        String token = request.getHeader("Token");
        //判断token是否为空, 如果为空, 响应401状态码。
        if(!StringUtils.hasLength(token)){ //jwt为空
            log.info("token为空, 响应401状态码");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

        //解析token，如果解析失败，返回错误结果（未登录）。
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
            log.info("token解析成功, 放行");
        } catch (Exception e) {
            log.info("token解析失败, 响应401状态码");
            response.setStatus(401);
            return;
        }

        //放行。
        log.info("令牌合法, 放行");
        chain.doFilter(request , response);

        //清空当前线程绑定的id
        CurrentHolder.remove();
    }
}
